//调用js浮层
var pageAdminAdd = null;
$('#k_add').live('click', function(){
	pageAdminAdd = $.layer({
		type: 1,
		title: false,
		area: ['600', 'auto'],
		border: [0],
		shade: [0.3,'#000'],
		closeBtn: [0, false],
		fadeIn: 500,
		move:".key_layer .tit",
		page:{dom:'.key_layer'}
	});
	//自设关闭
	$('.key_layer > .closeBtn,.key_layer .cancelLayer').live('click', function(){
		layer.close(pageAdminAdd);
        $("#adminNameText").val("");
        $("#adminPwdText").val("");
	});
	avoidDup = true;
	$('#addAdminArea').validationEngine('validate');
});		

var pageAdminSuperEdit = null;
$('.reviseSuper').live('click', function(){
	pageAdminSuperEdit = $.layer({
		type: 1,
		title: false,
		area: ['600', 'auto'],
		border: [0],
		shade: [0.3,'#000'],
		closeBtn: [0, false],
		fadeIn: 500,
		move:".key_layerSuperEdit .tit",
		page:{dom:'.key_layerSuperEdit'} 
	});
	
	//自设关闭
	$('.key_layerSuperEdit > .closeBtn,.key_layerSuperEdit .cancelLayer').live('click', function(){
		$("#adminPwdSuperEditText").val("");
		layer.close(pageAdminSuperEdit);
	});

	var adminName = $(this).attr("adminName").trim();
	var userId = $(this).attr("userId");
	$("#userSuperEditId").val(userId);
	$("#adminNameSuperEditText").val(adminName);
//	$("#adminName").val(adminName);
//	savaData.loadAjax(adminName);
//	$('#addAdminArea').validationEngine('validate');
});

var pageAdminEdit = null;
$('.revise').live('click', function(){
	pageAdminEdit = $.layer({
		type: 1,
		title: false,
		area: ['600', 'auto'],
		border: [0],
		shade: [0.3,'#000'],
		closeBtn: [0, false],
		fadeIn: 500,
		move:".key_layerEdit .tit",
		page:{dom:'.key_layerEdit'} 
	});
	
	//自设关闭
	$('.key_layerEdit > .closeBtn,.key_layerEdit .cancelLayer').live('click', function(){
		$("#adminPwdEditText").val("");
		layer.close(pageAdminEdit);
	});

	var adminName = $(this).attr("adminName").trim();
	var userId = $(this).attr("userId");
	$("#userEditId").val(userId);
	$("#adminNameEditText").val(adminName);
//	$("#adminName").val(adminName);
//	savaData.loadAjax(adminName);
//	$('#addAdminArea').validationEngine('validate');
});

var pageRightList = null;
$('.reviseRight').live('click', function(){
	pageRightList = $.layer({
		type: 1,
		title: false,
		area: ['600', 'auto'],
		border: [0],
		shade: [0.3,'#000'],
		closeBtn: [0, false],
		fadeIn: 500,
		move:".key_layerRightEdit .tit",
		page:{dom:'.key_layerRightEdit'} 
	});
	
	//自设关闭
	$('.key_layerRightEdit > .closeBtn,.key_layerRightEdit .cancelLayer').live('click', function(){
		layer.close(pageRightList);
	});

	var adminName = $(this).attr("adminName").trim();
	var userId = $(this).attr("userId");
	$("#userRightId").val(userId);
	var permissionId = $(this).attr("permissionId");
	$("#permissionId").val(permissionId);
	$("#adminNameRightEditText").val(adminName);
	savaData.loadRightAjax(userId);
	
	var permissionId = $("#permissionId").val();
	var perMsg = new RegExp($("#msgAdmTag").attr("idR"));
	var perPram = new RegExp($("#pramAdmTag").attr("idR"));
	var perRpt = new RegExp($("#rptAdmTag").attr("idR"));
	var perClie = new RegExp($("#clieAdmTag").attr("idR"));
	var perRsc = new RegExp($("#rscAdmTag").attr("idR"));
	var perLog = new RegExp($("#logAdmTag").attr("idR"));
	if(perMsg.test(permissionId)){$("#msgAdmTag").addClass("checked");}else{$("#msgAdmTag").removeClass("checked")}
	if(perPram.test(permissionId)){$("#pramAdmTag").addClass("checked");}else{$("#pramAdmTag").removeClass("checked")}
	if(perRpt.test(permissionId)){$("#rptAdmTag").addClass("checked");}else{$("#rptAdmTag").removeClass("checked")}
	if(perClie.test(permissionId)){$("#clieAdmTag").addClass("checked");}else{$("#clieAdmTag").removeClass("checked")}
	if(perRsc.test(permissionId)){$("#rscAdmTag").addClass("checked");}else{$("#rscAdmTag").removeClass("checked")}
	if(perLog.test(permissionId)){$("#logAdmTag").addClass("checked");}else{$("#logAdmTag").removeClass("checked")}
});	

var q ={
	//采集预警
	"loadData":function(data){
//		var userType = $("userTypeNow").val();
     	var objCount = data.returnData.length; //取得组织管理列表
     	window.curLen = objCount;
	   	var htmlList = "";
	   	var htmlListHead ="";
	   	
	   	for(var i=0;i<objCount; i++){
	   		var userId = data.returnData[i].userId;
	   		var adminName = data.returnData[i].userAccount;
	   		var userType = data.returnData[i].userType;//0：代表超级管理员；1：代表普通管理员；2：代表客户
	   		var permissionId=data.returnData[i].permissionId;
	   		if(userId!=0){
//	   			$("*[userId='1']").attr('readonly','readonly');
	   			//判断是否为超级管理员
			   	if(userType==0) { 
			   		htmlListHead = '<tr class="td"><td>'+adminName+'</td><td><a href="javascript:void(0);" userId='+userId+' adminName='+adminName+' class="reviseSuper">修改</a></td></tr>';
//			   		$("#adminNameEditText").attr('readonly','readonly');
			   	} else { 
					htmlList = htmlList+'<tr class="td"><td>'+adminName+'</td><td><a href="javascript:void(0);" userId='+userId+' adminName='+adminName+' class="reviseRight permissionId='+permissionId+'">编辑权限</a><a href="javascript:void(0);" userId='+userId+' adminName='+adminName+' class="revise">修改</a><a href="javascript:void(0); "userId='+userId+' adminName='+adminName+' class="removeBtn">删除</a></td></tr>';
//					$("#adminNameEditText").removeAttr('readonly','readonly');
			   	}
	   		}
	    }
	    var strHead = "<tr class='th'><th width='500'>管理员名</th><th>操作</th></tr>";
	    var strPage ="<tr class='pages'><td colspan='2'><div class='ui_page' id='pageArea'></div></td></tr>";
	    if(objCount<1){
	    	$(".ktab").html(strHead +"<tr class='td' colspan='3'>加载失败，请刷新重试！<td></td></tr>");	
	    }else{
	    	$(".ktab").html(strHead + htmlListHead + htmlList + strPage);	
	    }
//	    //给表格添加序号
//	   	var len = $('table tr').length;
//      for(var i = 1;i<len;i++){
//          $('table tr:eq('+i+') .numList').text(i);
//      }
	},	  		
	//public load ajax
	"publicAjax":function(pIndex,numList,selectJsonData){
		var _obj = $(".ktab");
		var url = basePath + "user/queryParams.do?pageIndex=" + pIndex + "&pageSize=" + numList + '&vtimes=' + new Date().getTime();
//		var userType = $("#userTypeNow").val();
		$.ajax({
			type: "POST",
			url: url,
			data:selectJsonData,
			error:function(request) {
				layer.msg("加载失败，请刷新重试！",2,-1);
		    },
		    success:function(data) {                    
                if (data.returnCode==10000) {
					if(data.returnData != null && data.returnData.length != 0) {
						q.loadData(data);
						paging.loadPage(data);
					} else if(data.returnData == null || data.returnData.length == 0) {
						$(".ktab").html("<tr class='th'><th width='500'>管理员名</th><th>操作</th></tr><tr class='td'><td colspan='4'>很遗憾，没有查询到相关数据！</td></tr>");
					}
                } else if(data.returnCode==999994){
                    setUserTimeout(data);
                }
            },
	        beforeSend:function(){
	        	var imgGif = "<p class='loadingGif'></p>";
	        	_obj.html(imgGif);
	    	} 
		});	  			
	}
}
//页面初始化
q.publicAjax(1,numList,selectJsonData);
//添加
var savaData={
	//权限编辑获取
	"getRightFormVal":function(data){
		//var adminName =data.returnData[0].adminName;
		var permissionId = data.returnData.permissionId;
		var perMsg = new RegExp($("#msgAdmTag").attr("idR"));
		var perPram = new RegExp($("#pramAdmTag").attr("idR"));
		var perRpt = new RegExp($("#rptAdmTag").attr("idR"));
		var perClie = new RegExp($("#clieAdmTag").attr("idR"));
		var perRsc = new RegExp($("#rscAdmTag").attr("idR"));
		var perLog = new RegExp($("#logAdmTag").attr("idR"));
		
		if(perMsg.test(permissionId)){$("#msgAdmTag").addClass("checked");}
		if(perPram.test(permissionId)){$("#pramAdmTag").addClass("checked");}
		if(perRpt.test(permissionId)){$("#rptAdmTag").addClass("checked");}
		if(perClie.test(permissionId)){$("#clieAdmTag").addClass("checked");}
		if(perRsc.test(permissionId)){$("#rscAdmTag").addClass("checked");}
		if(perLog.test(permissionId)){$("#logAdmTag").addClass("checked");}

	},
	//public loadRightAjax
	"loadRightAjax":function(userId){		
		$.ajax({
			type: "GET",
	        url: basePath+"user/selByUserMenus.do?userId="+userId,
	        success: function (data) {
                if (data.returnCode==10000) {
                    if (data.returnData!=null&& data.returnData.length!=0) {
                        savaData.getRightFormVal(data);
                    }else{
                           layer.msg("加载失败，请重试！",2,-1);
                    }
                } else if(data.returnCode==999994){
                    setUserTimeout(data);
                }
            },
	        error: function (message) {
	            layer.msg("加载失败123，请重试！",2,-1);
	        }
	    });	
	},
	
	
	//数据处理
	"addFrom":function(){
		var userType = 1;
		var userAccount = $("#adminNameText").val().trim();
		var userPwd =$("#adminPwdText").val().trim();
		var jsons = {
			"userType":userType,
			"userAccount":userAccount,
			"userPwd":userPwd
		};
		return jsons;
	},
	//添加
	"postAjax":function(){
		$.ajax({
			type: 'POST',
			url: basePath + 'user/addAdminUser.do',
			data: savaData.addFrom(),
			success: function (data) {
                if (data.returnCode==10000) {
                    layer.msg(data.returnMessage,1,10);   
					setTimeout(function(){
						try{
							$('#selectAll').trigger('click');
						}catch(e){}
					},1000);
//                    q.publicAjax(1,numList,selectJsonData); 
                    layer.close(pageAdminAdd);
                    $("#adminNameText").val("");
                    $("#adminPwdText").val("");
                }else if(data.returnCode==999994){
                    setUserTimeout(data);
                }else{
                    layer.msg(data.returnMessage,2,-1);
                    avoidDup = true;
                }
            },
			error: function (message) {
				layer.msg(message,2,-1);
			}
		});	
	},
	//修改管理员数据处理
	"editFrom":function(){
		var userType = 1;
		var userAccount = $("#adminNameEditText").val();
		var userPwd = $("#adminPwdEditText").val();
		var userId = $("#userEditId").val();
		var jsons = {
			"userId":userId,
			"userType":userType,
			"userAccount":userAccount,
			"userPwd":userPwd
		};
		return jsons;
	},
	//管理员修改接口--保存
	"postEditAjax":function(){
		$.ajax({
			type: 'POST',
			url: basePath + '/user/modify2.do',
			data: savaData.editFrom(),
			success: function (data) {
                if (data.returnCode==10000) {
                    layer.msg(data.returnMessage,1,10);   
                    layer.close(pageAdminEdit);
                    q.publicAjax(curPage,numList,selectJsonData);
                    $("#adminPwdEditText").val("");
                }else if(data.returnCode==999994){

                    setUserTimeout(data);

                }else{
                    layer.msg(data.returnMessage,2,-1);
                }
            },
			error: function (message) {
				layer.msg(message,2,-1);
			}
		});	
	},
	
	//修改管理员数据处理
	"editSuperFrom":function(){
		var userType = 1;
		var userAccount = $("#adminNameSuperEditText").val();
		var userPwd = $("#adminPwdSuperEditText").val();
		var userId = $("#userSuperEditId").val();
		var jsons = {
			"userId":userId,
			"userType":userType,
			"userAccount":userAccount,
			"userPwd":userPwd
		};
		return jsons;
	},
	//超级管理员修改接口--保存
	"postSuperEditAjax":function(){
		$.ajax({
			type: 'POST',
			url: basePath + '/user/modify.do',
			data: savaData.editSuperFrom(),
			success: function (data) {
                if (data.returnCode==10000) {
                    layer.msg(data.returnMessage,1,10);   
                    layer.close(pageAdminSuperEdit);
                    q.publicAjax(curPage,numList,selectJsonData);
                    $("#adminPwdSuperEditText").val("");
                }else if(data.returnCode==999994){

                    setUserTimeout(data);

                }else{
                    layer.msg(data.returnMessage,2,-1);
                }
            },
			error: function (message) {
				layer.msg(message,2,-1);
			}
		});	
	},
		
	
	//修改权限数据处理
	"editRightFrom":function(){
		var userType = 1;
		var userAccount = $("#adminNameRightEditText").val();
		var userId = $("#userRightId").val();
		var perm = [];
		if( $("#msgAdmTag").hasClass("checked")){perm.push($("#msgAdmTag").attr("idR"))}
		if( $("#pramAdmTag").hasClass("checked")){perm.push($("#pramAdmTag").attr("idR"))}
		if( $("#rptAdmTag").hasClass("checked")){perm.push($("#rptAdmTag").attr("idR"))}
		if( $("#rscAdmTag").hasClass("checked")){perm.push($("#rscAdmTag").attr("idR"))}
		if( $("#clieAdmTag").hasClass("checked")){perm.push($("#clieAdmTag").attr("idR"))}
		if( $("#logAdmTag").hasClass("checked")){perm.push($("#logAdmTag").attr("idR"))}
		var permission = perm.join(",");
		var jsons = {
			"userId":userId,
			"permission":permission,
			"userAccount":userAccount,
			"userType":userType
		};
		return jsons;
	},
	//权限修改接口--保存
	"postRightEditAjax":function(){
		$.ajax({
			type: 'POST',     
			url: basePath + 'user/modifyUserPro.do',	
			data: savaData.editRightFrom(),
			success: function (data) {
                if (data.returnCode==10000) {
                    layer.msg(data.returnMessage,1,10);   
                    layer.close(pageRightList);
                    q.publicAjax(curPage,numList,selectJsonData); 
                }else if(data.returnCode==999994){

                    setUserTimeout(data);

                }else{
                    layer.msg(data.returnMessage,2,-1);
                }
            },
			error: function (message) {
				layer.msg(message,2,-1);
			}
		});	
	}
}

//点击新增
$("#addAdminArea").validationEngine({"focusFirstField":true,"maxErrorsPerField":"1"});
var avoidDup = true;
$("#addAdminBtn").live("click",function(){
	if(avoidDup==false){
		return false;
	}
    var isSuccess = $('#addAdminArea').validationEngine('validate');
    if(isSuccess==true){
    	avoidDup = false;
	    savaData.postAjax();
    }
});

//超级管理员编辑事件
$("#editAdminSuperArea").validationEngine({"focusFirstField":true,"maxErrorsPerField":"1"});
$("#editAdminSuperBtn").live("click",function(){
	var isSuccess = $('#editAdminSuperArea').validationEngine('validate');
	if(isSuccess==true){
		savaData.postSuperEditAjax();
	}
});

//管理员编辑事件
$("#editAdminArea").validationEngine({"focusFirstField":true,"maxErrorsPerField":"1"});
$("#editAdminBtn").live("click",function(){
	var isSuccess = $('#editAdminArea').validationEngine('validate');
	if(isSuccess==true){
		savaData.postEditAjax();
	}
});

//权限编辑事件
$("#editAdminRightArea").validationEngine({"focusFirstField":true,"maxErrorsPerField":"1"});
$("#editAdminRightBtn").live("click",function(){
  var isSuccess = $('#editAdminRightArea').validationEngine('validate');
  if(isSuccess==true){
	  savaData.postRightEditAjax();
  }
});

//点击删除
$(".removeBtn").live("click",function(){
	var userName = $(this).attr("adminName").trim();
	var userId = parseInt($(this).attr("userId"));
	var userType=1;
	var objDel={
		"userName":userName,
		"userId":userId,
		"userType":userType
	};
	$.layer({
		title:"温馨提示：",
	    shade: [0],
	    area: ['230','auto'],
	    dialog: { 
	    	msg: '确定删除吗？',
		    btns: 2,  type: -1, 
		    btn: ['确定','取消'],
		    yes: function(){removes.removeAjax(objDel); }, 
		    no: function(){}
	    }
	});
}); 
var removes = {
	"removeAjax":function(objDel){
		$.ajax({
			type: 'POST',
			url: basePath + 'user/deleteUser.do?userName='+objDel.userName+'&userId='+objDel.userId+'&userType='+objDel.userType,
			success: function (data) {
                if (data.returnCode==10000) {
					layer.msg(data.returnMessage, 1, 10);
					if(window.curLen==1&&curPage>1){
						curPage = curPage-1;
					}
					q.publicAjax(curPage, numList, "");
                }else if(data.returnCode==999994){
                    setUserTimeout(data);
                }else{
                    layer.msg(data.returnMessage,1,-1);
                }
            },
			error: function (message) {
			    layer.msg("删除数据失败！<br>"+message,2,-1);
			}
		});		
	}
}

$(".infoLlist .ui_checkbox").live("click", function() {
	if($(this).hasClass("checked")) {
		$(this).removeClass("checked");
	} else {
		$(this).addClass("checked");
	}
});

//点击查询
$("#selectAll").live("click", function() {
	curPage = 1;
	qDataFun(curPage);
});
$('.enterSearch').keydown(function(e) {
	if(e.keyCode == 13) {
		curPage = 1;
		qDataFun(1);
	}
});
//点击触发换页的按钮
$("#pageArea .pNumBtn  a").live("click", function() {
	curPage = parseInt($(this).attr("toPage"));
	qDataFun(curPage);
});

//点击触发分批显示的按钮
$("#pageArea .columnsPage a").live("click", function() {
	numList = parseInt($(this).text());
	curPage = 1;
	qDataFun(curPage);
	subPage = $(this).index();
});
//跳转
$("#pageArea .gopg .btn").live("click", function() {
	curPage = parseInt($("#pageArea .gopg .txt").val());
	//判断输入的页数是否大于最大的页数
	if(curPage>countPage){
		curPage=countPage;
	}
	if(curPage>0){
		qDataFun(curPage);
	}
});

function qDataFun(curPages) {
	adminName = $("#adminNameSearch").val().trim();
	selectJsonData = null;
	selectJsonData = {
		account: adminName
	};
	q.publicAjax(curPages, numList, selectJsonData);
};